<template>
    <van-form @submit="onSubmit">
        <!--v-model:表设用户输入的值-->
            <van-field
                    v-model="editUser.currentValue"
                    :name="editUser.editKey"
                    :label="editUser.editName"
                    :placeholder="`请输入${editUser.editName}`"
            />

        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
    import {useRoute,useRouter} from "vue-router";
    import {ref,onMounted} from "vue";
    import myAxois from "../plugin/MyAxios";
    import {showFailToast, showSuccessToast} from "vant";
    import {getCurrentUser} from "../service/user";

    const route = useRoute();
    const router = useRouter();

    //接收用户页User传过来的参数，并将其集合成一个editUser
    const editUser = ref({
        //editKey对应：'username'  editName对应：'用户名'    currentValue对应：user.username
        editKey:route.query.editKey,
        editName:route.query.editName,
        currentValue:route.query.currentValue,
    })

    //获取当前登录用户信息
    const currentUser = ref('')
    onMounted(async () => {
        const res = await getCurrentUser();
        if(res.data.code === 0 && res.data.data){
            // showSuccessToast("成功！")
            currentUser.value = res.data.data;
        }else{
            // showFailToast("失败!")
        }
    })

    //提交修改后的数据给后端
    const onSubmit = (values) => {
        myAxois.post('/user/update',{
            //后端更新修改用户信息接口需要传入当前用户的id和和所要修改的信息
            //因为我们要修改的信息不是整个用户的信息，而是User页面中根据用户点击想修改哪一条的信息进行修改
            //所以[editUser.value.editKey]动态的获取用户所选择修改的项
            // : 分号前面是后端的参数名，后面是前端向后端传递的参数
            'id':currentUser.value.id,
            [editUser.value.editKey]:editUser.value.currentValue
        })
            .then(function (response) {
                console.log("/user/update",response);
                showSuccessToast("修改成功！")
                router.back()
            })
            .catch(function (error) {
                console.error("/user/update",error);
                showFailToast("修改失败！")
            });
    };
</script>

<style scoped>

</style>